#include<iostream>
#include<unistd.h>
#include<string.h>
#include<cerrno>
#include<assert.h>
#include<string>
#include<sys/types.h>
#include<sys/wait.h>

int main()
{
    //1.创建管道
    int pipefd[2]={0};
    int n=pipe(pipefd);
    if(n<0)
    {
        std::cout<<"pipe error,"<<errno<<":"<<strerror(errno)<<std::endl;
        return 1;
        //errno全局变量，如果c语言或系统调用出错会将errno设置为出错时的出错码。
        //strerror将错误码转化成错误描述
    }
    std::cout<<"pipefd[0]:"<<pipefd[0]<<std::endl;
    std::cout<<"pipefd[1]:"<<pipefd[1]<<std::endl;//pipefd[2] 0:读 1：写



    //2.创建子进程
    pid_t id=fork();
    assert(id !=-1);
    //3.关闭不需要的fd 父进程读 子进程写
    if(id==0)
    {
        //子进程
        close(pipefd[0]);//子进程关闭读端
        //4.开始通信
        std::string namestr="hello,I am child";
        int cnt=1;
        //组合消息打包,写入管道
        char buffer[1024];
        while(true)
        {
            snprintf(buffer,sizeof(buffer),"%s,cnt:%d,my pid:%d\n",namestr.c_str(),cnt++,getpid());
            write(pipefd[1],buffer,strlen(buffer));
            sleep(1);
        }
        close(pipefd[1]);
        

        exit(0);
    }
    //父进程
    close(pipefd[1]);//父进程关闭写端

    char buffer[1024];
    int cnt=0;
    while(true)
    {
        
        //sleep(1);
        int n=read(pipefd[0],buffer,sizeof(buffer)-1);
        if(n>0)
        {
            buffer[n]='\0';
            std::cout<<"I  am father,receive message from child: "<<buffer<<std::endl;

        }
        if(cnt++>5) break;
        

    }
    close(pipefd[0]);
    int status=0;
    waitpid(id,&status,0);
    std::cout<<"sig:"<<(status&0x7f)<<std::endl;
    return 0;
}
